//yarn add js-md5
import md5 from 'js-md5';
import {fileToBase64} from "@/units/file";


/**
 * 通过文件转base64计算文件MD5
 * @param file
 * @param length
 */
export function fileToMd5(file: File, length: 16 | 32 = 32): Promise<string> {
    return new Promise((resolve) => {
        fileToBase64(file).then(bas64 => () => resolve(stringToMd5(bas64, length))).catch(() => resolve(''))
    })
}

/**
 * 计算字符串MD5
 * @param str
 * @param length
 */
export function stringToMd5(str: string, length: 16 | 32 = 32): string {
    let md5_str: string = md5(str)
    if (length === 32) {
        return md5_str
    }
    return md5_str.substring(8, 24)
}
